# usage: python ConvertDirectoryContents.py --xslt ./converter.xsl --directory .
#
# Converts directory contents with converter specified and saves the generated xml in the current directory
#
#
import sys
import os
from optparse import OptionParser
from lxml import etree

def openFile(fileName, mode):
    file  = open(fileName, mode)
    if not file:
        print("Unable to open file %s for %s" % (fileName, mode))
        os.sys.exit(-1)
            
    return file


usage = "usage: %prog [options] arg1"
parser = OptionParser(usage=usage)
parser.add_option("--xslt", action="store", dest="xslt_filename", help="xslt used for the transform, e.g ./converter.xsl")
parser.add_option("--directory", action="store", dest="directory_of_files", help="directory of files to transform (defaults to current if not provided)")

(options, args) = parser.parse_args()

# Validate data source uri
if not options.xslt_filename:
    parser.error("Requires xslt.  Try --help for usage")
    sys.exit(-1)

if not options.directory_of_files:
    directory = '.'
else:
    directory = options.directory_of_files
    
xsltFilename = options.xslt_filename

xsltDocTree = etree.parse(xsltFilename)
assert(etree is not None)
transformer = etree.XSLT(xsltDocTree)


xmlOutAllTransformed = openFile("Transformed_Results.xml", "wa")


print("Transforming files in directory %s with converter %s" % (directory, xsltFilename))

for xmlInputFile in os.listdir(directory):
    xmlInputFilePath = ("%s/%s" % (directory, xmlInputFile))
    print("Transforming %s" % xmlInputFilePath)
    xmlSourceTree = etree.parse(xmlInputFilePath)
    assert(xmlSourceTree is not None)
    xmlDestinationTree = transformer(xmlSourceTree)
    xmlOutAllTransformed.write(str(xmlDestinationTree))
    
print("Results written to Transformed_Results.xml")
xmlOutAllTransformed.close()



